package main

import (
	"database/sql"
	"fmt"
)

var db *sql.DB

func initDB() {
	// 初始化数据库
	var err error
	db, err = sql.Open("sqlite3", "data.db")
	if err != nil {
		panic(err)
	}
}

func insertUser(username string, password string, addr string, phone string) error {
	stmt, err := db.Prepare("INSERT INTO User(username, password, addr, phone) values (?, ?, ?, ?);")
	if err != nil {
		return err
	}
	defer stmt.Close()
	res, err := stmt.Exec(username, password, addr, phone)
	if err != nil {
		return err
	}
	fmt.Println(res)
	return nil
}

func getUser(username string) (User, error) {
	var u User
	err := db.QueryRow("SELECT username, password, addr, phone from User where username = ?", username).Scan(&u.Username, &u.Password, &u.Addr, &u.Phone)
	return u, err
}

func insertGoods(ower string, status string, goodsType string, describe string, name string) error {
	stmt, err := db.Prepare("INSERT INTO Goods(ower, status, type, describe, name) values (?, ?, ?, ?, ?)")
	if err != nil {
		return err
	}
	defer stmt.Close()
	res, err := stmt.Exec(ower, status, goodsType, describe, name)
	if err != nil {
		return err
	}
	fmt.Println(res)
	return nil
}

func searchGoods(keywords string) ([]Goods, error) {
	keywords = "%" + keywords + "%"
	rows, err := db.Query("select ower, status, type, describe, name from Goods where describe like ? or name like ? or ower like ?", keywords, keywords, keywords)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	goodsList := make([]Goods, 0, 5)

	for rows.Next() {
		var g Goods
		err := rows.Scan(&g.Ower, &g.Status, &g.GoodsType, &g.Describe, &g.Name)
		if err != nil {
			return goodsList, err
		}
		goodsList = append(goodsList, g)
	}
	return goodsList, nil
}

func getGoods(name string, ower string) ([]Goods, error) {
	var goodsList []Goods
	if name == "" && ower != "" {
		rows, err := db.Query("select ower, status, type, describe, name from Goods where ower = ?", ower)
		if err != nil {
			return nil, err
		}
		for rows.Next() {
			var g Goods
			err := rows.Scan(&g.Ower, &g.Status, &g.GoodsType, &g.Describe, &g.Name)
			if err != nil {
				return goodsList, err
			}
			goodsList = append(goodsList, g)
		}

	} else if ower == "" && name != "" {
		rows, err := db.Query("select ower, status, type, describe, name from Goods where name = ?", name)
		if err != nil {
			return nil, err
		}
		for rows.Next() {
			var g Goods
			err := rows.Scan(&g.Ower, &g.Status, &g.GoodsType, &g.Describe, &g.Name)
			if err != nil {
				return goodsList, err
			}
			goodsList = append(goodsList, g)
		}
	} else {
		return nil, fmt.Errorf("参数错误")
	}
	return goodsList, nil
}

func updateUser(username string, password string, addr string, phone string) error {
	stmt, err := db.Prepare("update User set password = ?, addr = ?, phone = ? where username = ?")
	if err != nil {
		return err
	}
	defer stmt.Close()
	res, err := stmt.Exec(password, addr, phone, username)
	if err != nil {
		return err
	}
	fmt.Println(res)
	return nil
}
